package com.shsubway.activity.com;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.LazyLoaders;
import com.github.yoojia.inputs.StaticScheme;
import com.github.yoojia.inputs.ValueScheme;
import com.github.yoojia.inputs.WidgetAccess;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.shsubway.R;
import com.shsubway.activity.manger.HomeActivity;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.GroupEntity;
import com.shsubway.model.PostEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.Constant;
import com.shsubway.utils.SPUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.CountListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 *  包含注册 修改 忘记密码共用界面
 */
@RuntimePermissions
public class RgisterActivity extends BaseActivity implements Handler.Callback {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.user_name)
    MaterialEditText userName;
    @BindView(R.id.user_pwd)
    MaterialEditText userPwd;
    @BindView(R.id.user_pwd_again)
    MaterialEditText userPwdAgain;
    @BindView(R.id.user_yanzheng)
    MaterialEditText userYanzheng;
    @BindView(R.id.get_no_btn)
    Button getNoBtn;
    @BindView(R.id.user_please)
    MaterialEditText userPlease;
    @BindView(R.id.login_btn)
    Button loginBtn;
    @BindView(R.id.layout_pwd_again)
    LinearLayout layoutPwdAgain;
    @BindView(R.id.layout_plase)
    LinearLayout layoutPlase;
    @BindView(R.id.type_tv)
    TextView typeTv;
    @BindView(R.id.layout_yanzheng)
    LinearLayout layoutYanzheng;
    private AndroidNextInputs inputs;
    private WidgetAccess access;
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    GroupEntity groupEntity = null;
    Intent intent;
    Bundle bundle;
    int TYPE = 0;
    List<StaffEntity> listStaffs;
    StaffEntity staffEntityFromHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rgister);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        TYPE = intent.getIntExtra(Constant.TYPE, 0);
        setTitleBar(toolbar, TYPE == 0 ? "注册" : TYPE == 1 ? "忘记密码" : "修改密码");
        if (TYPE == 1) {
            typeTv.setVisibility(View.GONE);
            userPwd.setHint("请输入新密码");
            layoutPwdAgain.setVisibility(View.GONE);
            layoutPlase.setVisibility(View.GONE);
            loginBtn.setText("完成");
        } else if (TYPE == 2) {
            staffEntityFromHome = (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
            userName.setText(staffEntityFromHome.getStaff_phone());
            userName.setEnabled(false);
            userName.setShowClearButton(false);
            userPwd.setHint("旧密码");
            userPwdAgain.setHint("新密码");
            layoutYanzheng.setVisibility(View.GONE);
            typeTv.setVisibility(View.GONE);
            layoutPlase.setVisibility(View.GONE);
            loginBtn.setText("完成");
        }
        final Handler handler = new Handler(this);
        EventHandler eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
        initCheckNull();

    }

    private void initCheckNull() {
        inputs = new AndroidNextInputs();
    }

    private void addInputs() {
        inputs.add(userName, StaticScheme.NotBlank().msgOnFail("手机号码不能为空"), StaticScheme.ChineseMobile().msgOnFail("请输入正确的手机号码"));
        inputs.add(userPwd, StaticScheme.NotBlank().msgOnFail(TYPE == 2 ? "原密码不能为空" : "密码不能为空"));
        if (TYPE == 0) {
            inputs.add(userYanzheng, StaticScheme.NotBlank().msgOnFail("验证码不能为空"), StaticScheme.Digits().msgOnFail("验证码只能为数字"));
            LazyLoaders loader = new LazyLoaders(this);
            inputs.add(userPwdAgain, StaticScheme.NotBlank().msgOnFail("确认密码不能为空")
                    , ValueScheme.EqualsTo(loader.fromEditText(R.id.user_pwd)).msgOnFail("两次密码输入不一致"));
            inputs.add(userPlease, StaticScheme.NotBlank().msgOnFail("邀请码不能为空"));
        } else if (TYPE == 2) {
            inputs.add(userPwdAgain, StaticScheme.NotBlank().msgOnFail("新密码不能为空"));
        } else if (TYPE == 1) {
            inputs.add(userYanzheng, StaticScheme.NotBlank().msgOnFail("验证码不能为空"), StaticScheme.Digits().msgOnFail("验证码只能为数字"));
        }

    }

    /**
     * @param view
     */
    @OnClick({R.id.get_no_btn, R.id.login_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_no_btn:
                inputs.clear();
                inputs.add(userName, StaticScheme.NotBlank().msgOnFail("手机号码不能为空"), StaticScheme.ChineseMobile().msgOnFail("请输入正确的手机号码"));
                boolean passed = inputs.test();
                if (passed) {
                    RgisterActivityPermissionsDispatcher.onNeedWithCheck(this);
                }

                break;
            case R.id.login_btn:
                inputs.clear();
                addInputs();
                boolean passeds = inputs.test();
                if (passeds) {
                    //非空验证通过后进行 机构验证

                    if (TYPE == 0) {
                        /*注册*/
                        BmobQuery<GroupEntity> query = new BmobQuery<GroupEntity>();
                        query.addWhereEqualTo("niceName", userPlease.getText().toString().trim());
                        query.findObjects(new FindListener<GroupEntity>() {
                            @Override
                            public void done(List<GroupEntity> list, BmobException e) {
                                if (e == null) {
                                    if (list.size() == 0) {
                                        toast("请联系开发者获取正确的邀请码后进行注册。");
                                    } else if (list.size() == 1) {
                                        groupEntity = null;
                                        groupEntity = list.get(0);
                                        SMSSDK.submitVerificationCode("86", userName.getText().toString().trim(),
                                                userYanzheng.getText().toString().trim());
                                    }
                                } else {
                                    toast("获取配置失败，请联系软件公司");
                                }

                            }
                        });
                    } else if (TYPE == 1) {
                        /*忘记密码*/
                        BmobQuery<StaffEntity> query = new BmobQuery<StaffEntity>();
                        query.addWhereEqualTo("staff_phone", userName.getText().toString().trim());
                        query.findObjects(new FindListener<StaffEntity>() {
                            @Override
                            public void done(List<StaffEntity> list, BmobException e) {
                                if (e == null) {
                                    if (list.size() != 0) {
                                        listStaffs = list;
                                        SMSSDK.submitVerificationCode("86", userName.getText().toString().trim(),
                                                userYanzheng.getText().toString().trim());
                                    } else {
                                        toast("该号码未注册。");
                                    }
                                } else {
                                    toast("初始化配置失败，请联系软件开发公司。");
                                }
                            }
                        });


                    } else if (TYPE == 2) {
                        if (userPwd.getText().toString().trim().equals(staffEntityFromHome.getStaff_pwd())) {

                            staffEntityFromHome.setStaff_pwd(userPwdAgain.getText().toString().trim());
                            staffEntityFromHome.update(staffEntityFromHome.getObjectId(), new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if (e == null) {
                                        SPUtils.clear(context);
                                        HomeActivity.instance.finish();
                                        intent.setClass(context, LoginActivity.class);
                                        startActivity(intent);
                                        finish();
                                    } else {
                                        toast("密码修改失败，请联系软件开发公司。");
                                    }
                                }
                            });


                        } else {
                            toast("旧密码不正确请重新输入");
                        }


                    }


                }


                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        int event = msg.arg1;
        int result = msg.arg2;
        Object data = msg.obj;
        if (result == SMSSDK.RESULT_COMPLETE) {

            if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                saveGroup();
            } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                //验证码Ok
            }

        } else if (result == SMSSDK.RESULT_ERROR) {
            ((Throwable) data).printStackTrace();
            Log.e("data", data.toString());
            toast(data.toString());
        }


        return false;
    }

    /**
     * 保存用户信息 （实际为更新用户信息）
     */
    private void saveGroup() {

        if (TYPE == 0) {
            //先进行机构表的更新
            groupEntity.setMangerphone(userName.getText().toString().trim());
            groupEntity.update(groupEntity.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        checkUser();
                    } else {
                        toast("注册失败，请联系软件开发公司。");
                    }
                }
            });
        } else if (TYPE == 1) {
            //先进行机构表的更新
            StaffEntity staffEntity = listStaffs.get(0);
            staffEntity.setStaff_pwd(userPwd.getText().toString().trim());
            staffEntity.update(staffEntity.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        toast("密码找回成功");
                        finish();
                    } else {
                        toast("密码找回失败，请联系软件开发公司。");
                    }
                }
            });

        }

    }

    private void checkUser() {
        BmobQuery<StaffEntity> query = new BmobQuery<StaffEntity>();
        query.addWhereEqualTo("staff_phone", userName.getText().toString().trim());
        query.count(StaffEntity.class, new CountListener() {
            @Override
            public void done(Integer count, BmobException e) {
                if (e == null) {
                    if (count != 0) {
                        toast("该号码已经存在，请直接登录。");
                    } else {
                        saveUser();
                    }
                } else {
                    toast("注册失败，请联系软件开发公司。");
                }
            }
        });
    }

    private void saveUser() {
        BmobQuery<PostEntity> query = new BmobQuery<>();
        query.setLimit(100);
        query.order("createdAt")
                .findObjects(new FindListener<PostEntity>() {
                    @Override
                    public void done(List<PostEntity> object, BmobException e) {
                        if (e == null) {
                            // ...
                            StaffEntity staffEntity = new StaffEntity();
                            staffEntity.setStaff_phone(userName.getText().toString().trim());
                            staffEntity.setStaff_permissions(1);
                            staffEntity.setStaff_post(object.get(0).getPost());
                            staffEntity.setGroupId(groupEntity.getObjectId());
                            staffEntity.setStaff_pwd(userPwdAgain.getText().toString().trim());

                            staffEntity.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e == null) {
                                        toast("注册成功");
                                        startActivity(LoginActivity.class);
                                        finish();
                                    } else {
                                        toast("注册失败，请联系软件开发公司。");
                                    }
                                }
                            });


                            Log.e("oh==", object.toString());
                        } else {
                            // ...
                            Log.e("e==", e.toString());
                        }
                    }
                });


    }

    protected void startTimer() {
        CountDownTimer countDownTimer = new CountDownTimer(60 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                getNoBtn.setText(millisUntilFinished / 1000 + "s");
                getNoBtn.setClickable(false);//防止重复点击
                Log.e("CountDownTimer", "millisUntilFinished=" + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                //可以在这做一些操作,如果没有获取到验证码再去请求服务器
                getNoBtn.setClickable(true);//防止重复点击
                getNoBtn.setText("获取验证码");
            }
        };
        countDownTimer.start();
    }

    @NeedsPermission({Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onNeed() {
        Log.e("NEED==", "NEED");

        SMSSDK.getVerificationCode("86", userName.getText().toString().trim());
        toast("已发送");
        startTimer();
        //通过后发送验证码
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RgisterActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void OnShow(final PermissionRequest request) {
        request.proceed();
        Log.e("OnShow==", "OnShow");
        //用户第一拒绝后再次进入这个界面 如果这个权限是必须的则  request.proceed();
    }

    @OnPermissionDenied({Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void onDenied() {
        Log.e("onDenied==", "onDenied");
        //拒绝后来到这个方法 可以提示用户为什么我们要这个权限 退出此界面
        showHelp();
    }

    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void OnNever() {
        Log.e("OnNever==", "OnNever");
        showHelp();
    }

    private void showHelp() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.help);
        builder.setMessage(R.string.string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton("算了吧", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }

    // 启动应用的设置
    public void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }
}
